<?php
define('DOCTYPE_CUST',1);
define('DOCTYPE_LOC',2);
define('DOCTYPE_DISPATCH',3);

// Created by Khanh Nam
//convert from MySql datetime to your date
function formatMysqlDate($format, $date) {
    $ts = strtotime($date);
    return date($format, $ts);
}
function outputJsByList($list,$variableName){
    $rs=array();
   
    if(is_array($list) && count($list)>0){
        $count=0;
        foreach($list as $i=>$item){
            
            $rs[]=array(
                'key'=>$i,
                'value'=>$item
            );
        }
    }
    $rand=rand(0,9999999);
    $rs=json_encode($rs);
    Yii::app()->clientScript->registerScript($rand,"var $variableName=$rs;",  CClientScript::POS_HEAD);
    
}
function jsVariableGen($className,$keyAttr,$valueAttr,$variableName,$condition,$param=array(),$separator=' '){
    $list=$className::model()->findAll($condition,$param);
    //$rs[]= array('key'=>'','value'=>'N/A');
    $value="";
    if(count($list)>0){
        foreach($list as $stt=>$item){
            $rs[$stt]['key']=$item->$keyAttr;
            
            if(is_array($valueAttr)){
                $length=count($valueAttr);
                foreach($valueAttr as $i=>$name){
                    
                    $value.=$item->$name;
                    if($i<$length -1) $value.=$separator;
                }
                
                $rs[$stt]['value']=$value;
            }else{
                $rs[$stt]['value']=$item->$valueAttr;
            }
            
            
        }
    }
    $rand=rand(0,99999);
    Yii::app()->clientScript->registerScript("$rand","var $variableName= ".json_encode($rs).";",  CClientScript::POS_HEAD);
    return true;
    
}
function encrypt($data){
    
    return mcrypt_encrypt(MCRYPT_3DES, Yii::app()->params['encryptKey'], $data, MCRYPT_MODE_ECB);
}
function decrypt($encrypted){
    return mcrypt_decrypt(MCRYPT_3DES, Yii::app()->params['encryptKey'], $encrypted, MCRYPT_MODE_ECB);
}
function create_slug($str) {
    $str = trim($str);

    // replace space by -
    $str = preg_replace('/\s+/i', '-', $str);

    return $str;
}
function getImage($name,$folder,$width,$height){
   
    if(trim($name)=='' || !file_exists($folder)){
  
        return getImageBySize(Yii::app()->params['noImage'], $width, $height,false);
    }
    else{
  
        if(substr($folder, strlen($folder)-1,1)!='/'){
            $folder.='/';
        }
        if(!file_exists($folder.$name)){
            return getImageBySize(Yii::app()->params['noImage'], $width, $height,false);
        }
        return getImageBySize($folder.$name, $width, $height,false);
    }
}
function getImageBySize($path=NULL, $width=128, $height=128,$addPath=true) {
    if(! isset($path) || $path=='' || trim($path=='')){
       return getImageBySize(Yii::app()->params['noImage'], $width, $height,false);
    }
    if($addPath)
        $path='images/content/'.$path;
    
    $ext = getFileExt($path);
    clearstatcache();
    $directory = substr($path, 0, strlen($path) - strlen($ext));
    $fullPath = $directory . "_{$width}x{$height}" . $ext;
    
    
    if (file_exists($fullPath)) {
        return $fullPath;
    } else {
        
        if (file_exists($path)) {
            
            $img = Yii::app()->simpleImage->load($path);
            if($img->getWidth() > $width){
                $img->resizeToWidth($width);
                $img->save($fullPath);
                return $fullPath;
            }else{
                return $path;
            }
            
            
            
        }
    }

    
}

function getFileBodyName($name) {
    $pos = stripos($name, ".");
    if ($pos) {
        return substr($name, 0, $pos);
    } else {
        return "";
    }
}

function getFileExt($name) {
    $pos = stripos($name, ".");
    if ($pos) {
        return substr($name, $pos);
    } else {
        return "";
    }
}
function dbDateToHumanTiming($date){
    if(empty($date))return;
    return humanTiming(dbDateToTime($date));
}
function humanTiming($time) {

    $time = time() - $time; // to get the time since that moment
    
    $tokens = array(
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );

    foreach ($tokens as $unit => $text) {
        if ($time < $unit)
            continue;
        $numberOfUnits = floor($time / $unit);
        
        return $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : '');
    }
}

function stripExtraSpace($s) {
    for ($i = 0; $i < strlen($s); $i++) {
        $newstr = $newstr . substr($s, $i, 1);
        if (substr($s, $i, 1) == ' ')
            while (substr($s, $i + 1, 1) == ' ')
                $i++;
    }
    return $newstr;
}

function limitWord($str,$limit){
    $words=explode(' ', stripExtraSpace($str));
    $result="";
    $i=0;
    foreach($words as $word){
        $i++;
        $result.=$word;
        if($i>=$limit) break;
    }
    return $result;
}
function dbDateToTime($date){
    $datetime=explode(' ', $date);
    $date=explode('-',$datetime[0]);
    $time=explode(':',$datetime[1]);
    if(!empty($time)){
        return mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0]);
    }
    else{
        return mktime(0, 0, 0, $date[1], $date[2], $date[0]);
    }
}

function getUserByPermission($permission){
    $users=Yii::app()->db->createCommand('select u.email from tbl_useraccess ua 
        join tbl_users u on u.id=ua.user_id
        where find_in_set(:permission,ua.privilege)>0')->bindValues(array(
        'permission'=>$permission
    ))->queryAll();
    
    
    $rs=array();
    $s='';
    if($users!=NULL && count($users>0)){
        foreach($users as $i=>$item){
            
            $s.=$item['email'].',';
        }
    }
 
    $rs=explode(',', $s);
    return $rs;
}   

function getStateList(){
        return array(
            'AL'=>'AL',
            'AK'=>'AK',
            'AZ'=>'AZ',
            'AR'=>'AR',
            'CA'=>'CA',
            'CO'=>'CO',
            'CT'=>'CT',
            'DE'=>'DE',
            'FL'=>'FL',
            'GA'=>'GA',
            'HI'=>'HI',
            'ID'=>'ID',
            'IL'=>'IL',
            'IN'=>'IN',
            'IA'=>'IA',
            'KS'=>'KS',
            'KY'=>'KY',
            'LA'=>'LA',
            'ME'=>'ME',
            'MD'=>'MD',
            'MA'=>'MA',
            'MI'=>'MI',
            'MN'=>'MN',
            'MS'=>'MS',
            'MO'=>'MO',
            'MT'=>'MT',
            'NE'=>'NE',
            'NV'=>'NV',
            'NH'=>'NG',
            'NJ'=>'NJ',
            'NM'=>'NM',
            'NY'=>'NY',
            'NC'=>'NC',
            'ND'=>'ND',
            'OH'=>'OH',
            'OK'=>'OK',
            'OR'=>'OR',
            'PA'=>'PA',
            'PR'=>'PR',
            'RI'=>'RI',
            'SC'=>'SC',
            'SD'=>'SD',
            'TN'=>'TN',
            'TX'=>'TX',
            'UT'=>'UT',
            'VT'=>'VT',
            'VA'=>'VA',
            'WA'=>'WA',
            'WV'=>'WV',
            'WI'=>'WI',
            'WY'=>'WY',
        );
    }

function getUserRealname($email){
    $name=Yii::app()->db->createCommand('select real_name from tbl_users where email=:email')->bindParam('email', $email)->queryScalar();
    if($name!=false){
        return $name;
    }else{
        return NULL;
    }
    
}
